import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Not } from 'typeorm';
import { User } from '../../entities/user.entity';
import { CreateUserDto, UpdateUserDto, UserResponseDto } from '../../dto/user.dto';
import * as bcrypt from 'bcrypt';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  async create(createUserDto: CreateUserDto): Promise<UserResponseDto> {
    // 检查用户名是否已存在
    const existingUser = await this.usersRepository.findOne({
      where: [{ username: createUserDto.username }, { email: createUserDto.email }],
    });
    
    if (existingUser) {
      throw new HttpException('用户名或邮箱已存在', HttpStatus.CONFLICT);
    }

    // 哈希密码
    const hashedPassword = createUserDto.password; //await bcrypt.hash(createUserDto.password, 10);

    const user = this.usersRepository.create({
      ...createUserDto,
      password: hashedPassword,
      role: 0, // 默认角色为普通用户
    });

    await this.usersRepository.save(user);
    (user as any).id = undefined;
    return new UserResponseDto(user);
  }

  async findAll(page: number = 1, pageSize: number = 10, keyword?: string): Promise<{ data: UserResponseDto[], total: number }> {
    const query = this.usersRepository.createQueryBuilder('user');
    
    // 如果有关键字，添加模糊查询条件
    if (keyword) {
      query.where('user.username LIKE :keyword OR user.email LIKE :keyword', { keyword: `%${keyword}%` });
    }
    
    // 获取总数
    const total = await query.getCount();
    
    // 计算偏移量并获取分页数据
    const skip = (page - 1) * pageSize;
    const users = await query.skip(skip).take(pageSize).getMany();
    
    // 转换为响应DTO
    const userDtos = users.map(user => new UserResponseDto(user));
    
    return { data: userDtos, total };
  }

  async findOne(id: number): Promise<UserResponseDto> {
    const user = await this.usersRepository.findOneBy({ id });
    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.NOT_FOUND);
    }
    return new UserResponseDto(user);
  }

  async getProfile(id: number): Promise<User> {
    const user = await this.usersRepository.findOneBy({ id });
    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.NOT_FOUND);
    }
    return user;
  }

  async updateRole(id: number, role: number): Promise<UserResponseDto> {
    const user = await this.usersRepository.findOneBy({ id });
    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.NOT_FOUND);
    }

    user.role = role;
    await this.usersRepository.save(user);

    // 返回不包含密码的用户信息
    const { password, ...result } = user;
    return result;
  }

  async update(id: number, updateUserDto: UpdateUserDto): Promise<UserResponseDto> {
    const user = await this.usersRepository.findOneBy({ id });
    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.NOT_FOUND);
    }

    // 如果要更新密码，需要重新哈希
    // if (updateUserDto.password) {
    //   updateUserDto.password = await bcrypt.hash(updateUserDto.password, 10);
    // }

    // 检查用户名和邮箱是否与其他用户冲突
    if (updateUserDto.username || updateUserDto.email) {
      const conditions: any[] = [];
      if (updateUserDto.username) {
        conditions.push({ username: updateUserDto.username, id: Not(id) });
      }
      if (updateUserDto.email) {
        conditions.push({ email: updateUserDto.email, id: Not(id) });
      }
      
      const existingUser = await this.usersRepository.findOne({
        where: conditions,
      });
      if (existingUser) {
        throw new HttpException('用户名或邮箱已被其他用户使用', HttpStatus.CONFLICT);
      }
    }

    await this.usersRepository.update(id, updateUserDto);
    const updatedUser = await this.usersRepository.findOneBy({ id });
    return new UserResponseDto(updatedUser);
  }

  async remove(id: number): Promise<UserResponseDto> {
    // 先查询用户信息，检查角色
    const user = await this.usersRepository.findOneBy({ id });
    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.NOT_FOUND);
    }
    
    // 检查是否为管理员用户或 role == 1 的用户，禁止删除
    if (user.role === 1) {
      throw new HttpException('管理员用户不能删除', HttpStatus.FORBIDDEN);
    }
    
    const result = await this.usersRepository.delete(id);
    if (result.affected === 0) {
      throw new HttpException('删除失败，用户不存在', HttpStatus.NOT_FOUND);
    }
    
    // 返回删除的用户信息
    return new UserResponseDto(user);
  }

  /**
   * 更新用户状态（启用/禁用）
   * @param id 用户ID
   * @param isActive 是否启用
   * @returns 更新后的用户信息
   */
  async updateUserStatus(id: number, isActive: number): Promise<UserResponseDto> {
    const user = await this.usersRepository.findOneBy({ id });
    console.log("查询到的用户:", user);
    if (!user || user.role !== 0) {
      throw new HttpException('用户不存在或不是普通用户', HttpStatus.NOT_FOUND);
    }

    user.isActive = isActive === 1;
    await this.usersRepository.save(user);
    console.log("状态更新成功", user);
    return new UserResponseDto(user);
  }

}